package com.xdja.netty.handler.inbound;

import com.xdja.netty.conf.HttpManager;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageDecoder;
import io.netty.handler.codec.http.*;

import java.util.List;

/**
 * 返回json数据
 *
 * @author zk
 * @since 2018/7/24
 */
public class ResponseMappingDecoder extends MessageToMessageDecoder<String> {
    @Override
    protected void decode(ChannelHandlerContext ctx, String url, List<Object> out) throws Exception {
        HttpManager.Entry<HttpRequest, HttpContent> httpEntry = HttpManager.getMapping(url);
        if(httpEntry == null){
            HttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                    Unpooled.wrappedBuffer("no this url result".getBytes()));
            httpResponse.headers().set("transfer-encoding", "trunked");
            httpResponse.headers().set("content-type", "text/plain;charset=utf-8");
            ctx.channel().writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);
        } else {
            HttpResponse httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK,
                    httpEntry.getHttpContent().content());
            httpResponse.headers().set("transfer-encoding", "trunked");
            httpResponse.headers().set("content-type", "application/json;charset=utf-8");
            ctx.channel().writeAndFlush(httpResponse).addListener(ChannelFutureListener.CLOSE);

        }
    }
}
